<?php
/**
 * Case Model
 *
 * @property Service $Service
 */
class Work extends AdminAppModel
{

    public $useTable = 'cases';

/**
 * Display field
 *
 * @var string
 */
    public $displayField = 'title';


/**
 * belongsTo associations
 *
 * @var array
 */
    public $belongsTo = array(
        'Service' => array(
            'className' => 'Service',
            'foreignKey' => 'service_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    public $validate = array(
        'title' => array(
            'rule' => 'notEmpty',
        )
    );


    public function saveCase($requestData, $isUpdate=false, $originData=array())
    {
        $req = $requestData['Admin']['Case'];
        $originCase = empty($originData) ? array() : $originData['Admin'];
        // upload list_img
        //$listImg = $this->_uploadListImg($req, $isUpdate, $originCase);
        $listImg = $this->_uploadImg('list_img',$req, $isUpdate, $originCase);
        $homeImg = $this->_uploadImg('home_img', $req, $isUpdate, $originCase);
        // upload title_img
        //$titleImg = $this->_uploadTitleImg($req, $isUpdate, $originCase);
        $titleImg = $this->_uploadImg('title_img', $req, $isUpdate, $originCase);
        // parse features
        $features = $this->_parseFeatures($req);
        // upload case_img
        $caseImg = $this->_uploadCaseImg($req, $isUpdate);

        $data = array(
            'Work' => array(
                'title' => $req['title'],
                'service_id' => $req['service_id'],
                'desc' => $req['desc'],
                'list_img' => $listImg,
                'home_img' => $homeImg,
                'title_img' => $titleImg,
                'features' => $features,
                'images' => $caseImg,
                'priority' => $req['priority'],
                'updated' => time()
            )
        );
        if ($isUpdate) {
            $data['Work']['id'] = $req['id'];
        } else {
            $this->create();
        }
        if (!$this->save($data)) {
            throw new Exception("The data could not be saved.");
        }
        return $this->id;
    }

    public function getCase($id=null)
    {
        if ($id) {
            $this->id = $id;
            $cases = $this->read();

            $cases['Work']['features'] = json_decode($cases['Work']['features'], true);
            $cases['Work']['images'] = json_decode($cases['Work']['images'], true);
            $data = array(
                'Admin' => array(
                    'Case' => $cases['Work']
                )
            );
            return $data;
        } 
        return false;
    }

    /**
     * 处理列表缩图
     */
    private function _uploadListImg($requestData, $isUpdate=false, $orginData=array())
    {
        if ($isUpdate) {
            $orginImage = $orginData['Case']['list_img'];
        }
        $uploadFile = $this->upload($requestData['list_img'], 'list_img_', 'upload title img fail!');
        if (empty($uploadFile)) {
            return $orginImage; 
        }
        return $uploadFile;
    }

    /**
     * 处理列表缩图
     */
    private function _uploadImg($field, $requestData, $isUpdate=false, $orginData=array())
    {
        $orginImage = '';
        if ($isUpdate) {
            $orginImage = $orginData['Case'][$field];
        }
        $uploadFile = $this->upload($requestData[$field], "{$field}_", 'upload title img fail!');
        if (empty($uploadFile)) {
            return $orginImage; 
        }
        return $uploadFile;
    }

    /**
     * 处理标题的图片logo
     */
    private function _uploadTitleImg($requestData, $isUpdate=false, $orginData=array())
    {
        if ($isUpdate) {
            $orginImage = $orginData['Case']['title_img'];
        }
        $uploadFile = $this->upload($requestData['title_img'], 'title_img_', 'upload title img fail!');
        if (empty($uploadFile)) {
            return $orginImage; 
        }
        return $uploadFile;
    }

    protected function upload($data, $prefix, $exception='upload fail')
    {
        if ($data['size'] == 0) {
            return '';
        }
        if (is_uploaded_file($data['tmp_name'])) {
            $folder = 'uploads/'.date('Ymd');
            if (!is_dir($folder)) {
                mkdir($folder);
            }
            $pathinfo = pathinfo($data['name']);
            $extension = $pathinfo['extension'];
            $filename = uniqid($prefix).'.'.$extension;
            $path = $folder.'/'.$filename;
            if (move_uploaded_file($data['tmp_name'], $path)) {
                return $path;
            }
        }
        throw new Exception($exception);

    }

    /**
     * 解析案例说明
     */
    private function _parseFeatures($requestData)
    {
        $features = $requestData['features'];
        return json_encode($features);
    }

    /**
     * 处理案例图片的上传
     */
    private function _uploadCaseImg($requestData, $isUpdate)
    {
        if ($isUpdate) {
            $originData = $this->findById($requestData['id']);
            $originImages = json_decode($originData['Work']['images'], true);
        }

        $paths = array();
        foreach ($requestData['images'] as $i => $image) {
            if ($isUpdate && $image['size'] == 0) {
                if ($isUpdate) {
                    $paths[$i] = isset($originImages[$i]) ? $originImages[$i] : '';
                } else {
                    $paths[$i] = '';
                }
            } else {
                $paths[$i] = $this->upload($image, 'case_', "upload $i case image fail");
            }
        }
        return json_encode($paths);
    }
}
